
const db = wx.cloud.database()

Page({
  data:{
    recipeList:[],//菜谱列表变量
    page:1,
    pagesize:3,
    isMore:true,//是否有下页更多
    id:'',//菜谱分类的id
  },
  onLoad(options){
    console.log(options)
    this.data.id = options.id
    wx.setNavigationBarTitle({
      title:options.name
    })
    this._getRecipeList()
  },
  _goToRecipeDetail(e){
    let {id,title} = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/recipeDetail/recipeDetail?id=${id}&title=${title}`,
    })
  },
  onReachBottom(){
    this.data.page++
    this._getRecipeList()
  },
  //获取当前分类下的菜谱列表
  async _getRecipeList(){

    if( !this.data.isMore ){
      return
    }
      wx.showLoading({
        title: '正在请求...',
      })
      let recipeTypeId = this.data.id
      let page = this.data.page 
      let pagesize = this.data.pagesize
      let skip = (page-1)*pagesize
      let recipesResult = await db.collection('re-recipes').where({
        recipeTypeId
      }).limit(pagesize).skip(skip).orderBy( 'addtime','desc' ).get()
      console.log(recipesResult,'aaa')
      if( recipesResult.data.length == 0 ){
        this.setData({
          isMore:false
        })
      }

      //以下 处理每一个数据的_openid返回promise，拿到用户表中的用户信息
      let userPromises = []
      recipesResult.data.forEach(item=>{
        //console.log(item._openid)
         let p = db.collection('re-users').where({
           _openid:item._openid
         }).get()
         userPromises.push( p )
      })

      let users = await Promise.all(userPromises)
      //console.log( users,'222' )
      recipesResult.data.forEach((item,index)=>{
          item.userInfo = users[index].data[0]
      })
      //以上是处理每一个数据的_openid返回promise，拿到用户表中的用户信息

      wx.hideLoading()
      this.setData({
        recipeList:this.data.recipeList.concat( recipesResult.data  )
      })
  }
})